package prender;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

@SuppressWarnings("serial")
public class Attribute extends TagSupport {
	
	private static final Logger logger = Logger.getLogger("Attribute");

	private String name;
	public void setName(String name) {
		this.name = name;
	}
	
	private Object value;
	public void setValue(Object value) {
		this.value = value;
	}

	@Override
	public int doStartTag() throws JspException {
		return SKIP_BODY;
	}
	
	@Override
	public int doEndTag() throws JspException {
		if (logger.isDebugEnabled()) {
			logger.debug(String.format("doEndTag: enter, this = [%x], request = [%s], response = [%s]",
				this.hashCode(),
				Utility.getObjectSignature(pageContext.getRequest()),
				Utility.getObjectSignature(pageContext.getResponse())));
		}
		Tag parentTag = getParent();
		if ((parentTag == null) || !(parentTag instanceof Slot)) {
			if (logger.isDebugEnabled()) {
				logger.debug("doEndTag: leave, parent is not a slot, ignore");
			}
			return EVAL_PAGE;
		}
		
		MyRequest myRequest = Utility.getMyRequest(pageContext.getRequest());
		if (myRequest == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("doEndTag: leave, my request not found, ignore");
			}
			return EVAL_PAGE;
		}
		Slot slot = (Slot)parentTag;
		slot.setAttribute(name, value);
		if ((value != null) && (value instanceof InitializableBean)) {
			((Slot)getParent()).addBeanForInitialization((InitializableBean)value);
		}
		if (logger.isDebugEnabled()) {
			logger.debug(String.format("doEndTag: set attribute, name = [%s], value = [%s]", name, Utility.getObjectSignature(value)));
			logger.debug("doEndTag: leave");
		}
		return EVAL_PAGE;
	}
}
